import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Card,
  Descriptions,
  Image,
  Tag,
  Button,
  Carousel,
  Empty,
  Spin,
  InputNumber,
  message,
  Space,
} from 'antd';
import {
  LeftOutlined,
  ShoppingCartOutlined,
  ShoppingOutlined,
} from '@ant-design/icons';
import { getMedicineDetail } from '@/api/medicine';
import type { MedicineDTO } from '@/types/medicine';
import { addToCart } from '@/utils/cart';
import styles from './styles.module.less';

const MedicineDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [medicine, setMedicine] = useState<MedicineDTO>();
  const [quantity, setQuantity] = useState(1);

  const fetchMedicineDetail = async () => {
    if (!id) return;
    setLoading(true);
    try {
      const res = await getMedicineDetail(parseInt(id));
      setMedicine(res.data.data);
    } catch (error) {
      console.error('获取药品详情失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchMedicineDetail();
  }, [id]);

  const handleBack = () => {
    navigate(-1);
  };

  const handleQuantityChange = (value: number | null) => {
    if (value && value > 0) {
      setQuantity(value);
    }
  };

  const handleAddToCart = () => {
    if (!medicine) return;
    
    const images = medicine.images?.split(',').filter(Boolean) || [];
    const firstImage = images[0];

    addToCart({
      id: medicine.id!,
      name: medicine.name,
      image: firstImage || '/images/fallback.png',
      price: medicine.price!,
      quantity,
      stock: medicine.stock!,
    });

    message.success('已添加到购物车');
  };

  const handleBuyNow = () => {
    if (!medicine) return;
    
    const images = medicine.images?.split(',').filter(Boolean) || [];
    const firstImage = images[0];

    addToCart({
      id: medicine.id!,
      name: medicine.name,
      image: firstImage || '/images/fallback.png',
      price: medicine.price!,
      quantity,
      stock: medicine.stock!,
    });

    navigate('/cart');
  };

  if (loading) {
    return (
      <div className={styles.loading}>
        <Spin size="large" />
      </div>
    );
  }

  if (!medicine) {
    return (
      <Card className={styles.medicineDetail}>
        <Empty description="暂无药品信息" />
      </Card>
    );
  }

  const images = medicine.images?.split(',').filter(Boolean) || [];

  return (
    <div className={styles.medicineDetail}>
      <Card
        title={
          <div className={styles.header}>
            <Button icon={<LeftOutlined />} onClick={handleBack}>
              返回
            </Button>
            <h2 className={styles.title}>{medicine.name}</h2>
          </div>
        }
      >
        <div className={styles.content}>
          <div className={styles.gallery}>
            {images.length > 0 ? (
              <Carousel autoplay className={styles.carousel}>
                {images.map((image, index) => (
                  <div key={index} className={styles.imageWrapper}>
                    <Image
                      src={image}
                      alt={`${medicine.name}-${index + 1}`}
                      className={styles.image}
                      fallback="/images/fallback.png"
                    />
                  </div>
                ))}
              </Carousel>
            ) : (
              <div className={styles.noImage}>
                <Empty description="暂无图片" />
              </div>
            )}
          </div>

          <Card className={styles.purchase}>
            <div className={styles.price}>
              <span className={styles.symbol}>￥</span>
              <span className={styles.amount}>{medicine.price?.toFixed(2)}</span>
            </div>
            <div className={styles.stock}>
              库存：{medicine.stock}
            </div>
            <div className={styles.quantity}>
              <span className={styles.label}>数量：</span>
              <InputNumber
                min={1}
                max={medicine.stock}
                value={quantity}
                onChange={handleQuantityChange}
              />
            </div>
            <div className={styles.actions}>
              <Space size="large">
                <Button
                  type="primary"
                  ghost
                  icon={<ShoppingCartOutlined />}
                  onClick={handleAddToCart}
                >
                  加入购物车
                </Button>
                <Button
                  type="primary"
                  icon={<ShoppingOutlined />}
                  onClick={handleBuyNow}
                >
                  立即购买
                </Button>
              </Space>
            </div>
          </Card>

          <Descriptions
            title="基本信息"
            bordered
            column={{ xs: 1, sm: 2, md: 3 }}
            className={styles.descriptions}
          >
            <Descriptions.Item label="药品名称">{medicine.name}</Descriptions.Item>
            <Descriptions.Item label="药品分类">
              <Tag color="blue">{medicine.categoryName}</Tag>
            </Descriptions.Item>
            <Descriptions.Item label="生产厂家">{medicine.manufacturer}</Descriptions.Item>
            <Descriptions.Item label="规格">{medicine.specification}</Descriptions.Item>
          </Descriptions>

          {medicine.description && (
            <Card title="药品描述" className={styles.section}>
              <div className={styles.text}>{medicine.description}</div>
            </Card>
          )}

          {medicine.usageMethod && (
            <Card title="用法用量" className={styles.section}>
              <div className={styles.text}>{medicine.usageMethod}</div>
            </Card>
          )}

          {medicine.contraindication && (
            <Card title="禁忌" className={`${styles.section} ${styles.warning}`}>
              <div className={styles.text}>{medicine.contraindication}</div>
            </Card>
          )}
        </div>
      </Card>
    </div>
  );
};

export default MedicineDetail; 